from argparse import ArgumentParser
from configparser import ConfigParser
from typing import Optional
import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader

HTML_TEMPLATE_FILE = "html.template"


def config_path() -> Optional[str]:
    """获取脚本执行的输入参数, 并返回脚本运行时指定的配置文件名"""
    parser = ArgumentParser()
    parser.add_argument('-f', '--filename', help='指定配置文件名', required=False)
    args = parser.parse_args()
    return args.filename


def read_config(path: str):
    """获取指定配置文件的配置项，会忽略section，仅保留key-value"""
    config = ConfigParser()
    config.read(path, encoding="utf-8")
    return {k: v for section in config.sections() for k, v in config.items(section)}


class BaseClass:
    web_data = {}

    def __init__(self):
        self.config_path = config_path()
        self.config_idx = 0
        self.config = {}
        if self.config_path:
            self.config_idx = int(self.config_path[len("config_"):-len(".ini")])
            self.config = read_config(self.config_path)

    def create_html(self):
        """根据模板文件，生成 html文件"""
        if not os.path.exists(HTML_TEMPLATE_FILE):
            return

        display_content = self._render_template(HTML_TEMPLATE_FILE)

        file_name = "{}.html".format(self.config_idx)
        with open(file_name, 'w', encoding="utf-8") as fd:
            fd.write(display_content)

    # 渲染模板文件
    def _render_template(self, template_file):
        env = Environment(loader=FileSystemLoader(os.path.curdir))
        tpl = env.get_template(template_file)

        return tpl.render(config=self.config, result=self.web_data,
                          current_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
